package com.newly.driver.mqtt.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.newly.api.business.feign.MQTTReceiverClient;
import com.newly.common.core.utils.SpringContextUtil;
import com.newly.driver.mqtt.utils.MqttUtils;
import com.newly.driver.mqtt.utils.ReturnResult;
import com.newly.transfer.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class MQTTReceiveCallback implements MqttCallbackExtended {

    @Autowired
    RedisUtils redisUtils;

    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        //log.info("连接断开，可以做重连");
        MqttUtils.reConnect();
    }

    public void connectComplete(boolean reconnect, String serverURI){
//        redisUtils = SpringContextUtil.getBean(RedisUtils.class);
//        MqttUtils.batchSubTopic("+");
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("服务器回调:发送成功：" + token.isComplete());
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        log.info("接收消息主题 : " + topic);
        log.info("接收消息内容 : " + new String(message.getPayload()));

        JSONObject messageJson = new JSONObject();
        try {
            redisUtils = SpringContextUtil.getBean(RedisUtils.class);
            MQTTReceiverClient mqttReceiverClient = SpringContextUtil.getBean(MQTTReceiverClient.class);
            //消息主体转json格式
            messageJson = JSONUtil.parseObj(new String(message.getPayload()));

//            if (topic.indexOf("/command/request/request-id=0x10000001") == -1){
//                //token验证
//                boolean success = TokenUtils.tokenCheck(messageJson);
//                if(success==false){
//                    JSONObject result = ReturnResult.error(messageJson,"-32000");
//                    MqttUtils.responseMessage(topic, result);
//                    return;
//                }
//            }

            //消息分发
            if(topic.indexOf("/command/response/request-id") >= 0){
//                mqttDeviceClient.messageArrived(topic,messageJson);
                redisUtils.set(topic,JSONUtil.toJsonStr(messageJson),10);
            }
            ReceiveService receiveService = new ReceiveService();
            receiveService.messageArrived(topic,messageJson,redisUtils,mqttReceiverClient);
        }catch (Exception e){
            //统一处理异常，同时避免基类MqttCallback接收到异常后中断连接
            JSONObject result = new JSONObject();
            Class<? extends Exception> aClass = e.getClass();
            String exceptionName = aClass.getName();
            switch (exceptionName){
                case "cn.hutool.json.JSONException":
                    result = ReturnResult.error(messageJson,"-32601");
                    MqttUtils.responseMessage(topic, result);
                    break;
                default:
//                    result = ReturnResult.error(messageJson,"-32603");
                    break;
            }
        }
    }
}